package network2;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

public class MultiChatServerThread extends Thread {
	MultiChatServer server;
	Socket socket;
	boolean tFlag = true;
	ObjectOutputStream send;
	ObjectInputStream receive;
	
	public MultiChatServerThread(MultiChatServer s, Socket socket){
		this.server = s;
		this.socket = socket;
		this.start();
		
	}
	public void run(){
		try{
			send = new ObjectOutputStream(socket.getOutputStream());
			receive =new ObjectInputStream(socket.getInputStream());
			
			while(tFlag){
			
				Object o = receive.readObject();
				if(o instanceof SocketData 
						&& SocketData.serialVersionUID == 100000){
						
					SocketData sd = (SocketData)o;
					
					
					if(sd.getCommand().equals("login")){
						server.clients.put(sd.getUser(), this);
					
						Collection<String> c= server.clients.keySet();
						Object temp[] = c.toArray();
						server.list.setListData(temp);
						
						sd.setCommand("userlist");
						sendUserList(sd, c);

						server.dataSet(sd);
						
					}else if(sd.getCommand().equals("serverdown")){
						tFlag=false;
						server.dataSet(sd);
						sendMsg(sd);
						
					}else if(sd.getCommand().equals("logout")){
						tFlag = false;
						server.dataSet(sd);
						sendMsg(sd);
						server.clients.remove(sd.getUser());
						Collection<String> c= server.clients.keySet();
						Object temp[] = c.toArray();
						server.list.setListData(temp);
					}else{
						server.dataSet(sd);
						sendMsg(sd);
						
					}
					
				}
			}
			
		}catch(Exception ex){
			try{
				InetAddress ia = socket.getInetAddress();
				String rIP = ia.getHostAddress();
				System.out.println("오류 클라이언트 : " + rIP);
				ex.printStackTrace();
			}catch(Exception ex2){
				
			}
		}
	}
	
	// 클라이언트가 접속되면 서버가 저장하고 있는 모든 유저 목록을 object에 담아 모든 유저에게 전송함.
	public void sendUserList(SocketData sd, Collection<String> c){
		Iterator<String> it = c.iterator();
		Vector v = new Vector<>();
		
		while(it.hasNext()){
			v.add(it.next());
		}
		
		sd.setObj(v);

		sendMsg(sd);
	}
	
	public void sendMsg(SocketData sd){
		try{
			Collection<String> c = server.clients.keySet();
			Iterator<String> it = c.iterator();
			while(it.hasNext()){
				MultiChatServerThread t = server.clients.get(it.next());
				t.send.writeObject(sd);	
			}
			
		}catch(Exception ex){}
		
	}

}



